#!/bin/sh

# 配置文件路径
TCPA_CONFIG_PATH="/etc/parameters/tcpa_monitor"
TCPA_CONFIG_FILE="/etc/parameters/tcpa_monitor/tcpa_cfg.json"
WHITELIST_CONFIG_FILE="/etc/parameters/tcpa_monitor/whitelist_cfg.json"
# 测试环境配置
# TCPA_CONFIG_PATH="conf"
# TCPA_CONFIG_FILE="conf/tcpa_cfg.json"
# WHITELIST_CONFIG_FILE="conf/whitelist_cfg.json"

# tcpa_cfg.sh tcpa "[{\"vrf_name\":\"vrf1\",\"enable\":false,\"max_connect\":10,\"server_ip\":\"192.168.1.1\",\"server_port\":8000,\"listen_port\":9000}]"
# tcpa_cfg.sh whitelist "[{\"vrf_name\":\"vrf1\",\"src_ip\":\"10.0.0.0/8\",\"src_port\":0,\"dst_ip\":192.168.0.0/16,\"dst_port\":0}]"

# 校验是否为root用户，先判断EUID是否被定义
if [ -n "$EUID" ]; then
    if [ $EUID -ne 0 ]; then
        echo "This script must be run as root"
        exit 1
    fi
fi

if [ $# -lt 1 ]; then
    echo "Usage: $0 <help|tcpa|whitelist>"
    exit 1
fi

if [ ! -d $TCPA_CONFIG_PATH ]; then
    mkdir -p $TCPA_CONFIG_PATH
    if [ $? -ne 0 ]; then
        echo "Error: Failed to create $TCPA_CONFIG_PATH. check if the directory is writable by current user"
        exit 1
    fi
fi

if [ $1 = "tcpa" ]; then
    if [ $# -lt 2 ]; then
        echo "Usage: $0 tcpa \"[{\"vrf_name\":\"vrf1\",\"enable\":false,\"max_connect\":10,\"server_ip\":\"192.168.1.1\"}]\""
        exit 1
    fi
    if [ $# -eq 3 ]; then
        TCPA_CONFIG_FILE=$3
    fi
    # echo "Configuring ctpa_cfg to $TCPA_CONFIG_FILE"
    echo $2 > $TCPA_CONFIG_FILE
    if [ $? -ne 0 ]; then
        echo "Error: Failed to write to $TCPA_CONFIG_FILE. check if the file is writable by current user"
        exit 1
    fi
elif [ $1 = "whitelist" ]; then
    if [ $# -lt 2 ]; then
        echo "Usage: $0 whitelist \"[{\"vrf_name\":\"vrf1\",\"src_ip\":\"10.0.0.0/8\",\"src_port\":0,\"dst_ip\":192.168.0.0/16,\"dst_port\":0}]\""
        exit 1
    fi
    if [ $# -eq 3 ]; then
        WHITELIST_CONFIG_FILE=$3
    fi
    # echo "Configuring whitelist to $WHITELIST_CONFIG_FILE"
    echo $2 > $WHITELIST_CONFIG_FILE
    if [ $? -ne 0 ]; then
        echo "Error: Failed to write to $WHITELIST_CONFIG_FILE. check if the file is writable by current user"
        exit 1
    fi
else
    echo "Usage: $0 <help|tcpa|whitelist>"
    echo "Example: $0 tcpa \"[{\"vrf_name\":\"vrf1\",\"enable\":false,\"max_connect\":10,\"server_ip\":\"192.168.1.1\"}]\""
    echo "Example: $0 whitelist \"[{\"vrf_name\":\"vrf1\",\"src_ip\":\"10.0.0.0/8\",\"src_port\":0,\"dst_ip\":192.168.0.0/16,\"dst_port\":0}]\""
    exit 1
fi

